//
//  Label.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/4/24.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit
extension UILabel {
    
    /// 修改文本的大小颜色
    ///
    /// - Parameters:
    ///   - title: title
    ///   - color: color
    ///   - font: font
    func changeLabelTextStyle(title:String, color:UIColor, font:UIFont,isSpace:Bool = false) -> Void {
        let attributeString:NSMutableAttributedString = NSMutableAttributedString(string: self.text!)
        if self.text!.range(of: title) == nil {
            return
        }
        let range: Range<String.Index> = self.text!.range(of: title)!
        let firstLoc:NSRange = attributeString.string.range(range: range)!
        let firstLocation = firstLoc.location
        let titleRange = NSMakeRange(firstLocation,title.count)
        attributeString.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: titleRange)
        attributeString.addAttribute(kCTFontAttributeName as NSAttributedStringKey, value: font, range: titleRange)
        if isSpace {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 7
        attributeString.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0,(self.text?.count)!))
        }
        self.attributedText = attributeString
    }
    
    
    /// 计算文本大小
    ///
    /// - Parameters:
    ///   - text: 文字
    ///   - font: font
    ///   - size: size
    /// - Returns: 大小
    func sizeWithText(text: NSString, font: UIFont, size: CGSize) -> CGRect {
        //        let attributes = [NSFontAttributeName: font]
        let attributes = [
            NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue):  font
            ] as [NSAttributedStringKey : Any]
        
        let option = NSStringDrawingOptions.usesLineFragmentOrigin
        //        let rect:CGRect = text.boundingRect(with: size, options: option, attributes: attributes, context: nil)
        let rect:CGRect = text.boundingRect(with: size, options: option, attributes: attributes, context: nil)
        return rect;
    }
    
    
    /// 修改文本间隙
    ///
    /// - Parameter space: 间隙大小
    func changeContentSpace(space:CGFloat) {
        let attributeString:NSMutableAttributedString = NSMutableAttributedString(string: self.text!)
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = space
//        attributeString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0,(self.text?.count)!))
        attributeString.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0,(self.text?.count)!))
        self.attributedText = attributeString
        self.sizeToFit()
        
    }
}
